package map;

import java.util.*;

public class MinimumIndexSumOfTwoLists599 {
    public String[] findRestaurant(String[] list1, String[] list2) {
        Map<String, Integer> map = new HashMap<>();
        for (int i = 0; i < list2.length; i++) {
            if (!map.containsKey(list2[i])) {
                map.put(list2[i], i);
            }
        }
        int min = Integer.MAX_VALUE;
        Set<String> result = new HashSet<>();
        for (int i = 0; i < list1.length; i++) {
            if (map.containsKey(list1[i])) {
                int sum = map.get(list1[i]) + i;
                if (sum == min) {
                    result.add(list1[i]);
                }
                if (sum < min) {
                    result.clear();
                    result.add(list1[i]);
                    min = sum;
                }
            }
        }
        return result.toArray(new String[]{});
    }
}
